import { useLocalStorage } from "@/hooks/useLocalStorage"
import { RootState } from "@/store"
import { RouteMeta, RouteRecordRaw } from "vue-router"
import { Module } from "vuex"
import { userManagement } from "../UserManagement"
import { IAsideActions, IAsideGetter, IAsideMenu, IAsideMutations, IAsideState } from "./types"

const state: IAsideState = {
    menuRoutes: [],
}

const actions: IAsideActions = {
    generateMenuRoutes({ commit }, routes: RouteRecordRaw[]) {
        const adminMenuRoutes = routes.filter(r => r.meta.parentPath === "/admin")
        commit("_generateMenuRoutes", composeMenu(adminMenuRoutes))
        return true
    }
}
function composeMenu(routes: RouteRecordRaw[]) {
    const tempRoutes = [];
    let obj = {} as IAsideMenu;
    routes.forEach(r => {
        const meta: RouteMeta = r.meta
        obj.path = r.path;
        Object.keys(meta).forEach(key => obj[key] = meta[key] || '')
        if (r.children?.length) {
            obj.children = composeMenu(r.children)
        }
        tempRoutes.push(obj);
        obj = {}
    })
    return tempRoutes;
}

const mutations: IAsideMutations = {
    _generateMenuRoutes(state: IAsideState, payload: RouteRecordRaw[]) {
        state.menuRoutes = payload;
        console.log(payload);
        
        useLocalStorage().setLocalStorage("menuRoutes", payload)

    }
}
const getters: IAsideGetter = {}

export const aside: Module<IAsideState, RootState> = {
    namespaced: true,
    state,
    actions,
    mutations,
    getters,
    modules: {
        userManagement
    }
}
